layui.use(['form', 'table'], function() {
    var form = layui.form;
    var table = layui.table


    //获取所有项目并渲染
    function xrAllProjectList() {
        let url = getApiHttpUrl('api/projectmanage/getallcaneditproject');
        HttpRequest.request({
            url:url,
            type:'POST',
            dataType:'JSON',
            data:{},
            success:function (datas) {
                if (datas.status == "YES") {
                    xrProjectListForm(datas.data);
                } else {
                    layer.msg(datas.info);
                }
            },
            error:function (e) {
                layer.msg("服务器开小差了~");
            }
        });
    }

    //渲染项目列表
    function xrProjectListForm(data) {
        let htmlStr = "";
        for (let i in data) {
            htmlStr += '<option value="'+ data[i]['id'] +'">'+ data[i]['name'] +'</option>';
        }
        $("#allProjectList").append(htmlStr);
        form.render('select');
    }

    form.on('select(allProjectList)', function (data) {
        xrAllCategoryList();
        $("#searchContent").val('');
        form.render('select');
        setTimeout(() => {
            $("#searchApiBtn").click();
        }, 10);
    });

    form.on('select(allCategoryList)', function (data) {
        form.render('select');
        setTimeout(() => {
            $("#searchApiBtn").click();
        }, 10);
    });

    //获取所有项目列表并渲染
    function xrAllCategoryList() {
        let Cache = scarecrowCache();
        let projectId = $("#allProjectList").val();
        let cacheKey = "PROJECT_CATEGORY_EDIT_" + projectId;
        let data = Cache.getKey(cacheKey, false);
        if (data === false) {
            let loadingIndex= layer.load(1);
            let url = getApiHttpUrl('api/projectmanage/getallcategory');
            HttpRequest.request({
                url:url,
                type:'POST',
                dataType:'JSON',
                async:false,
                data:{
                    projectId:$("#allProjectList").val()
                },
                success:function (datas) {
                    layer.close(loadingIndex);
                    if (datas.status == "YES") {
                        data = datas.data;
                        Cache.setKey(cacheKey, data, 14400);
                    } else {
                        layer.msg(datas.info);
                        return false;
                    }
                },
                error:function (e) {
                    layer.close(loadingIndex);
                    layer.msg("服务器开小差了~");
                    return false;
                }
            });
        } else {
        }
        xrCategoryTable(data);
    }

    //渲染接口列表
    function xrCategoryTable(data) {
        let htmlStr = '<option value="0">请选择分类</option>';
        for (let i in data) {
            htmlStr += '<option value="'+ data[i]['id'] +'">'+ data[i]['name'] +'</option>';
        }
        $("#allCategoryList").empty().append(htmlStr);
        form.render('select');
    }

    $("#searchApiBtn").click(function () {
        if ($("#allProjectList").val() < 1) {
            layer.msg("请选择项目");
            return false;
        }
        xrAllApiList();
    });


    //获取所有项目列表并渲染
    function xrAllApiList() {
        let loadingIndex= layer.load(1);
        let url = getApiHttpUrl('api/apidoc/getapidoclist');
        HttpRequest.request({
            url:url,
            type:'POST',
            dataType:'JSON',
            data:{
                projectId:$("#allProjectList").val(),
                categoryId:$("#allCategoryList").val(),
                apiName:$('#searchContent').val()
            },
            success:function (datas) {
                layer.close(loadingIndex);
                if (datas.status == "YES") {
                    xrApiTable(datas.data);
                } else {
                    layer.msg(datas.info);
                }
            },
            error:function (e) {
                layer.close(loadingIndex);
                layer.msg("服务器开小差了~");
            }
        });
    }

    //渲染接口列表
    function xrApiTable(data) {
        let htmlStr = "";
        $("#showAllApiTable > tbody").empty();
        for (let i in data) {
            htmlStr += '<tr>'+
                '<td>'+ data[i]['title'] +'</td>'+
                '<td>'+ data[i]['request_method'] +'</td>'+
                '<td>'+ data[i]['url'] +'</td>'+
                '<td>'+ data[i]['update_time'] +'</td>'+
                '<td><a class="layui-btn layui-btn-xs" onclick="editApi('+ data[i]['id'] +')">编辑</a><a class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteApi('+ data[i]['id'] +')">删除</a></td>'+
                '</tr>';
        }

        $("#showAllApiTable > tbody").append(htmlStr);
    }


    $("#addApiBtn").click(function () {
        EDIT_NOW_PROJECT_ID = $("#allProjectList").val();
        let index = layer.open({
            title:"添加接口",
            type: 2,
            content: getHttpUrl('page/project/create_api.html'),
            area: ['100%', '100%'],
            end:function () {
                $("#searchApiBtn").click();
            },
            success:function () {
                layer.full(index);
            }
        });
    });

    (()=>{
        $("#searchApiBtn").click();
        xrAllProjectList();
    })();
});

EDIT_NOW_PROJECT_ID = 0;
EDIT_NOW_API_ID = 0;
/**
 * 编辑接口
 * @param projectId
 */
function editApi(apiId) {
    EDIT_NOW_API_ID = apiId;
    let index = layer.open({
        title:'编辑接口',
        type: 2,
        content: getHttpUrl('page/project/edit_api.html'),
        area: ['100%', '100%'],
        end:function () {
            $("#searchApiBtn").click();
        },
        success:function () {
            layer.full(index);
        }
    });
}

/**
 * 删除项目
 * @param projectId
 */
function deleteApi(apiId) {
    let index = layer.open({
        type: 1
        ,title: false //不显示标题栏
        ,closeBtn: false
        ,area: '300px;'
        ,shade: 0.8
        ,id: apiId
        ,btn: ['确定', '取消']
        ,btnAlign: 'c'
        ,content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">你知道吗？亲！<br>你删除了该接口之后就不能再恢复了哟，请再次确认是否删除~</div>'
        ,yes: function(){
            //进行删除处理
            HttpRequest.request({
                url:getApiHttpUrl('api/apidoc/deleteapi'),
                type:"POST",
                dataType:"JSON",
                data:{
                    apiId:apiId
                },
                success:function (datas) {
                    layer.close(index);
                    layer.msg(datas.info);
                },
                error:function () {
                    layer.close(index);
                    layer.msg("服务器错误，请稍后再试~");
                }
            });
        }
        ,end: () => {
            $("#searchApiBtn").click();
        }
    });
}